package com.yundou.www.wrpc.core.net;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;


/**
 * @author wangweiwei
 * @since 2021/7/22
 */
public class ClientBusinessHandler extends SimpleChannelInboundHandler<String> {

    private static Map<Long , WRpcResponse> map1 = new HashMap<>(16);

    private static Map<Long , CountDownLatch> map2 = new HashMap<>(16);


    public static WRpcResponse getResult(Long id) {

        return map1.get(id);
    }

    public static void doEnd(Long id, CountDownLatch downLatch) {
        map2.put(id, downLatch);

    }


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {

        if (StringUtils.isBlank(s)) {
            return;
        }
//        System.out.println(s);
        WRpcResponse response = JSON.parseObject(s, WRpcResponse.class);
        if (response.getCode() == 9999) {
            //心跳
            return;
        }
        map1.put(response.getId() , response);
        CountDownLatch countDownLatch = map2.get(response.getId());
        if (Objects.nonNull(countDownLatch)) {
            //完成
            countDownLatch.countDown();
        }

        //设置原来的线程响应
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
        //发送心跳
        WRpcRequest request = new WRpcRequest();
        request.setCheckSession(1);
        ctx.channel().writeAndFlush(JSON.toJSONString(request)+"$");

    }
}
